package com.example.wx_basketball.controller;

import com.example.wx_basketball.entity.User;
import com.example.wx_basketball.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Author  zxy
 * Date  2023/3/6 下午 10:28
 */
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Map<Object, Object> loginIn(String loginName, String password) {
        Map<Object, Object> map = new HashMap<>();

        User user = userService.getUserByLoginName(loginName);

        // 用户名不存在
        if (user == null) {
            map.put("code", 500);
            map.put("result", "用户名错误");
            System.out.println("用户名错误！");
        }
        else {
            String pw = user.getPassword();
            // 密码错误
            if (!pw.equals(password)) {
                map.put("code", 400);
                map.put("result", "密码错误");
                System.out.println("密码错误！");
            }
            // 登录成功
            else {
                map.put("code", 200);
                map.put("result", "登录成功");
                map.put("userId", user.getUserId());
                map.put("loginName", user.getLoginName());
                System.out.println("登录成功！");
            }
        }
        return map;
    }

    @PostMapping("/register")
    public Map<Object, Object> register(String loginName, String password) {
        Map<Object, Object> map = new HashMap<>();

        int id = userService.register(loginName, password);
        if (id > 0) {
            map.put("code", 200);
            map.put("result", "注册成功");
            System.out.println("注册成功！");
        }
        else {
            map.put("code", 500);
            map.put("result", "注册失败");
            System.out.println("注册失败！");
        }
        return map;
    }


    @GetMapping("/getUser")
    public User getUserById(int userId) {
        System.out.println("成功获取用户");
        return userService.getUserByUserId(userId);
    }

    @PostMapping("/updateUserInfo")
    public int updateUser(int userId, String loginName, String password, String introduce) {
        System.out.println(userId + " " + loginName);
        int res = userService.updateUserInfo(loginName, password, introduce, userId);
        System.out.println();
        return res;
    }
}
